package top.kaoshanji.p2ch09a;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 代码清单-p2ch09a-291页a：从文件系统加载字节代码的类加载器
 * author kaoshanji
 * ^_^
 * create time 2025/1/28 16:00
 */
public class FileSystemClassLoader extends ClassLoader {

    private Path path;

    public FileSystemClassLoader(Path path) {
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        try {
            byte[] classData  = getClassData(name);
            return defineClass(name, classData, 0, classData.length);
        } catch (IOException e) {
            throw new ClassNotFoundException();
        }

    }

    private byte[] getClassData(String className) throws IOException {

        Path classFilePath = classNameToPath(className);
        return Files.readAllBytes(classFilePath);

    }

    private Path classNameToPath(String className) {
        return path.resolve(className.replace('.', File.separatorChar) + ".class");
    }


}
